{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import numpy as np\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def swish(x):\n",
    "  return x*tf.nn.sigmoid(x)\n",
    "  \n",
    "def selu(x):\n",
    "  with tf.name_scope('elu') as scope:\n",
    "    alpha = 1.6732632423543772848170429916717\n",
    "    scale = 1.0507009873554804934193349852946\n",
    "    return scale*tf.where(x>=0.0,x,alpha*tf.nn.elu(x))\n",
    "    \n",
    "def relu(x):\n",
    "  return tf.nn.relu(x)\n",
    "  \n",
    "def activation(x):\n",
    "  #\n",
    "  return swish(x)#使用swish(x)函数的效果是最好的！\n",
    "\n",
    "def initialize(shape,stddev=0.1):\n",
    "  return tf.truncated_normal(shape,stddev=stddev)\n",
    "  #return tf.zeros(shape) \n",
    "###截断的高斯分布，因为高斯分布里面生成的值是随机的，可能出现超过普遍值区域的偏值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "init_learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "#Create the model\n",
    "L1_units_count = 100\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "tf.shape(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#exponetial lr decay\n",
    "epoch_steps = tf.to_int64(tf.div(60000,tf.shape(x)[0]))\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "current_epoch=global_step//epoch_steps\n",
    "decay_times=current_epoch\n",
    "current_learning_rate = tf.multiply(init_learning_rate,\n",
    "                    tf.pow(0.575,tf.to_float(decay_times))) #0.575的decay_times次方"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "W_1 = tf.Variable(initialize([784,L1_units_count],\n",
    "         stddev=np.sqrt(2/784))) #W_1使用核初始化\n",
    "b_1 = tf.Variable(tf.constant(0.001,shape=[L1_units_count]))\n",
    "logits_1 = tf.matmul(x,W_1)+b_1\n",
    "output_1 = activation(logits_1)\n",
    "\n",
    "L2_units_count = 10\n",
    "W_2 = tf.Variable(initialize([L1_units_count,\n",
    "            L2_units_count],\n",
    "            stddev=np.sqrt(2/L1_units_count)))\n",
    "b_2=tf.Variable(tf.constant(0.001,shape=[L2_units_count]))\n",
    "logits_2 = tf.matmul(output_1,W_2)+b_2\n",
    "\n",
    "y = logits_2\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "    \n",
    "l2_loss=tf.nn.l2_loss(W_1)+tf.nn.l2_loss(W_2)\n",
    "total_loss = cross_entropy +4e-5*l2_loss\n",
    "\n",
    "optimizer=tf.train.AdamOptimizer(current_learning_rate)\n",
    "gradients=optimizer.compute_gradients(total_loss)\n",
    "train_step = optimizer.apply_gradients(gradients)\n",
    "\n",
    "train_step = tf.train.AdamOptimizer(\n",
    "  current_learning_rate).minimize(\n",
    "  total_loss,global_step=global_step)\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess=tf.InteractiveSession()\n",
    "tf.global_variables_initializer().run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "for step in range(3000):\n",
    "    batch_xs,batch_ys = mnist.train.next_batch(100)\n",
    "    lr=1e-2\n",
    "    _,loss,l2_loss_value,total_loss_value,current_lr_value=\\\n",
    "      sess.run(\n",
    "     [train_step,cross_entropy,l2_loss,total_loss,\n",
    "      current_learning_rate],\n",
    "     feed_dict={x:batch_xs,y_:batch_ys,\n",
    "       init_learning_rate:lr})\n",
    "    if(step+1)%100==0:\n",
    "        print('step %d,entropy loss: %f,l2_loss: %f,total loss: %f'%\n",
    "        (step+1,loss,l2_loss_value,total_loss_value))\n",
    "        print(sess.run(accuracy,feed_dict={x:mnist.test.images,\n",
    "        y_:mnist.test.labels}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
